package com.dotflat.rest.controller;

import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.AreableObjectBaseService;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;

@Slf4j
public class WriteableRestfulBaseController <T1, T2 extends AreableObjectBaseService<T1>, P extends AreableObjectBasePO>
        extends RestfulBaseController<T1, T2, P>{

    @ApiOperation(value = "增加一条记录")
    @PostMapping()
    public StatusResponse add(HttpServletRequest req,
                              @RequestHeader(TICKET) String ticket, P param){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");
        BindedBabyVO defaultBaby = loginUser.getDefaultBaby();

        T1 ret = baseService.add(defaultBaby.getAreaId(), defaultBaby.getId(), param);

        List<T1> tmp = new ArrayList<>();
        tmp.add(ret);

        return StatusResponse.success(tmp);
    }

    @ApiOperation(value = "逻辑删除一个或多个对象")
    @DeleteMapping()
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "ids", value = "对象id数组", required = false, dataType = "string[]"),
            @ApiImplicitParam(paramType = "formData", name = "id", value = "对象id， 和ids二选一", required = false, dataType = "string")
    })
    public StatusResponse delete(HttpServletRequest req,
                                 @RequestHeader(TICKET) String ticket, String[] ids, String id ){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");
        BindedBabyVO defaultBaby = loginUser.getDefaultBaby();

        if (StringUtils.isNotEmpty(id)) {
            AreableObjectBasePO param = new AreableObjectBasePO();
            param.setId(id);

            baseService.delete(defaultBaby.getAreaId(), defaultBaby.getId(), param);
        }else if(ids != null && ids.length > 0){
            baseService.delete(defaultBaby.getAreaId(), defaultBaby.getId(), ids);
        }else{
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误!");
        }

        return StatusResponse.success();
    }

}
